#!/usr/bin/perl
# use Data::Dumper;
# 该命令一次性列出制定Motor的状态值。如果希望以观察的模式，建议结合watch命令

%MOTOR_PATH;  # Motor Mapping  "A" => "Dirver Path"
%SENSOR_PATH;  # SENSOR Mapping  "1" => "Dirver Path"
%SENSOR_NAME;  # SESON PATH.

getMotorInfo();
getSensorInfo();

#### print out the Motor infor
foreach $motorName (sort keys %MOTOR_PATH){
	$MName=$motorName;
	$speed=`cat $MOTOR_PATH{$motorName}/speed`;
	$position=`cat $MOTOR_PATH{$motorName}/position`;
	$duty_cycle=`cat $MOTOR_PATH{$motorName}/duty_cycle`;
	$stop_action=`cat $MOTOR_PATH{$motorName}/stop_action`;
	$time_sp=`cat $MOTOR_PATH{$motorName}/time_sp`;
	$state=`cat $MOTOR_PATH{$motorName}/state`;
	write;
}
#### print out the SENSO info

print"\n  port   Name          Mode         value0  value1  value2  value3  value4  value5  value6  value7 driver_path\n";
print"  ----- -------------- ------------ ------- ------- ------- ------- ------- ------- ------- ------- -----------------------------\n";

$~='STDOUT_S';
foreach $idx (sort keys %SENSOR_PATH){
	chop($mode=`cat $SENSOR_PATH{$idx}/mode`);
	for($i=0;$i<8;$i++){
		$valuefile="$SENSOR_PATH{$idx}/value$i";
		`cat $valuefile >/dev/null 2>&1`;
		if($? ==0){
			chop($value[$i]=`cat $valuefile`);
		}else{
			$value[$i]="-";
		}
	}

	write;
}


	
# Get Motor Info
sub getMotorInfo{
	for($i=0;$i<5;$i++){
		my $add="/sys/class/tacho-motor/motor$i/address";
		if(-e $add){
			my $content=`cat $add`;
			(my $port)=$content=~/out((A|B|C|D))/;
			$MOTOR_PATH{$port}="/sys/class/tacho-motor/motor$i";
		}
	}
}

# Get Sensor Info
sub getSensorInfo{
	my $SENSOR_DIR="/sys/class/lego-sensor";
	opendir (DIR, $SENSOR_DIR) || die "Error in opening dir $SENSOR_DIR\n";
	while(($filename = readdir(DIR))){
		next if($filename!~/sensor/);  # 非sensor 开头的文件忽略
		chop (my $address=`cat $SENSOR_DIR/$filename/address`);
		chop (my $sensorname=`cat $SENSOR_DIR/$filename/driver_name`);
		$SENSOR_NAME{$address}=$sensorname;
		$SENSOR_PATH{$address}="$SENSOR_DIR/$filename";
	}
	closedir(DIR);
}

format STDOUT_TOP =
  Motor speed position duty_cycle count_per_rot stop_action time_sp state
  ----- ----- -------- ---------- ------------- ----------- ------- ------
.

format STDOUT =
  @<<<< @>>>> @>>>>>>> @>>>>>>>>> @>>>>>>>>>>>> @>>>>>>>>>> @>>>>>> @>>>>>>
  $MName, $speed ,$position,$duty_cycle,$count_per_rot,$stop_action,$time_sp,$state
.

format STDOUT_TOP_S =
  Motor speed position duty_cycle count_per_rot stop_action time_sp state
  ----- ----- -------- ---------- ------------- ----------- ------- ------
.

format STDOUT_S =
  @<<<< @<<<<<<<<<<<<<< @<<<<<<<<<< @>>>>>> @>>>>>> @>>>>>> @>>>>>> @>>>>>> @>>>>>> @>>>>>> @>>>>>> @>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  $idx, $SENSOR_NAME{$idx},$mode,$value[0],$value[1],$value[2],$value[3],$value[4],$value[5],$value[6],$value[7],$SENSOR_PATH{$idx} 
.
